package com.aitaoxue.palx.fragment;

import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;

import com.aitaoxue.palx.R;
import com.aitaoxue.palx.adapter.CourseAdapter;
import com.aitaoxue.palx.api.remote.AitaoXueApi;
import com.aitaoxue.palx.base.ListBaseAdapter;
import com.aitaoxue.palx.base.NoCacheBaseListFragment;
import com.aitaoxue.palx.bean.Course;
import com.aitaoxue.palx.bean.CourseList;
import com.aitaoxue.palx.bean.ListEntity;
import com.aitaoxue.palx.db.course.CourseContext;
import com.aitaoxue.palx.db.course.CourseContext.Type;
import com.aitaoxue.palx.service.CourseService.Callback;
import com.aitaoxue.palx.ui.CourseDetailActivity;
import com.aitaoxue.palx.util.GsonUtil;
import com.aitaoxue.palx.util.IntentUtil;

public class CourseFragment extends NoCacheBaseListFragment implements Callback {

	private static final String TAG = CourseFragment.class.getSimpleName();

	@Override
	protected int getLayoutId() {
		return R.layout.fragment_course_list;
	}

	@Override
	protected ListEntity parseList(byte[] response) throws Exception {
		String res = new String(response);

		CourseList list = GsonUtil.GsonToBean(res, CourseList.class);

		// CourseService intentService=new CourseService();
		// intentService.setCallback(this);
		// Intent intent=new Intent(getActivity(), intentService.getClass());
		// intent.putExtra("courses", list);
		// intent.putExtra("type", courseType);
		// getActivity().startService(intent);

		// 改用asyncTask实现
		// 在adapter中实现

		return list;
	}

	@Override
	protected void sendRequestData(Map<String, String> map) {
		AitaoXueApi.showOrder(String.valueOf(mCurrentPage), courseType,
				mCacheHandler);
	}

	@Override
	protected ListBaseAdapter getListAdapter() {
		return new CourseAdapter(courseType, getActivity());
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Course course = (Course) mAdapter.getItem(position);

		ImageView icon = (ImageView) view.findViewById(R.id.new_order_icon);
		icon.setVisibility(View.GONE);

		if (CourseContext.getInstance().isOrderNew(course.getOrder_id())) {
			CourseContext.getInstance().saveEntity(course, courseType, 0, null);

			CourseContext.getInstance().saveType(Integer.parseInt(courseType),
					Type.DELETE);
			// 发送广播,改变订单红点
			Intent broadIntent = new Intent(IntentUtil.PUSH_NEW_ORDER);
			getActivity().sendBroadcast(broadIntent);
		}
		Intent intent = new Intent(getActivity(), CourseDetailActivity.class);
		intent.putExtra("course", course);
		intent.putExtra("type", courseType);
		startActivity(intent);
	}

	@Override
	public void onFinished(List<String> list) {
		System.out.println("here");
		List<String> tmp = list;
	}
	
	

}
